import json
from utils.douBaoAI import douBaoAI
from models import App, UserAnswer, Question, ScoringResult, db

AI_TEST_SCORING_SYSTEM_MESSAGE = '''
你将作为一位严谨的判题专家，我会提供以下信息：
        "```\n" +
      应用名称，
      【【【应用描述】】】，
      题目信息和用户选择的列表：格式为 [{"question": "题目","choice": "用户选择"}]
      每个question的组成模式如下：
      {"title":"题目标题","options":[{"value":"选项内容","key":"A","result":"评判类应用结果","score":"得分类应用得分"}]}
      请根据上述信息，按以下步骤对用户进行评价：
      1.要求：给出明确的评价结果，包含评价名称（需简短）和评价描述（需详细，超过 200 字）
      2.若为得分类应用，需计算得分，并在以下 JSON 格式基础上增加 "resultScore": "用户得分" 字段
      3.json格式：
      {"resultName": "评价名称", "resultDesc": "评价描述"}
      4. 返回格式必须为 JSON 对象;
      5. "评价描述"最后那里可以加作一下简单的总结,告知用户哪些地方有待提升,如果是”得分类“,就说哪些可以去学习一下哪些知识点，如果是测评类，可以根据测评内容基于相关意见
'''


async def AIdoTestScore(choices: list[str], app: App, id: int) -> UserAnswer:
    appId = app.id
    question: Question = Question.query.filter(Question.appId == appId).first()
    questionContent = question.questionContent
    questionContentList = json.loads(questionContent)
    userPrompt = generate_user_prompt(app=app, choices=choices, questionContentList=questionContentList)
    systemPrompt = AI_TEST_SCORING_SYSTEM_MESSAGE
    stream = True
    result = await douBaoAI.query(system_message=systemPrompt, user_message=userPrompt, stream=stream)
    result = json.loads(result)
    userAnswer: UserAnswer = UserAnswer.query.get(id)
    userAnswer.appId = appId
    userAnswer.appName = app.appName
    userAnswer.choices = json.dumps(choices, ensure_ascii=False, indent=4)
    userAnswer.resultName = result.get('resultName', '没有评价名称')
    userAnswer.resultDesc = result.get('resultDesc', '没有评价描述')
    if app.appType == 0:
        userAnswer.resultScore = int(result.get('resultScore', None))
    db.session.commit()
    return userAnswer


class questionAnswerDto():
    def __init__(self, question: object, choice: str):
        self.question = question
        self.choice = choice

    def to_dict(self):
        return {
            'question': self.question,
            'choice': self.choice
        }


def generate_user_prompt(app: App, choices: list[str], questionContentList: list[object], ):
    appName = app.appName
    appDesc = app.appDesc
    appType = "测评类" if app.appType == 1 else "得分类"
    questionAnswerDtos: list[questionAnswerDto] = list()
    for i in range(len(choices)):
        questionAnswerDtos.append(questionAnswerDto(questionContentList[i], choices[i]))
    questionAnswerJson: str = json.dumps([dto.to_dict() for dto in questionAnswerDtos],ensure_ascii=False, indent=4)
    userPrompt = f'''
        请帮我生成一个应用名称是：{appName},
                    应用描述是: {appDesc}，
                    应用类型是: {appType},
                    题目信息和用户选择:{questionAnswerJson}
                    的评分策略的集合
    '''
    return userPrompt
